﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.ComponentModel;
using Motif;
using Classes;
using Scoreloop.CoreSocial.API;
using System.Windows.Controls.Primitives;
using Scoreloop.CoreSocial.API.Model;

namespace MemoBoss
{
    public partial class Options : UserControl
    {
        Action returnMethod;
        Action NavigateToCollectionPage;
        Action SetBackgroundPicture;
        Action StartAccelerometer;

        public Options(Action callback, Action navigateToCollectionPage, Action SetBGPicture, Action startAccelerometer)
        {
            StartAccelerometer = startAccelerometer;
            SetBackgroundPicture = SetBGPicture;
            NavigateToCollectionPage = navigateToCollectionPage;
            returnMethod = callback;
            InitializeComponent();
            this.DataContext = App.SettingsInstance;
            if (App.SettingsInstance.UseAllImagesSetting) UseAllOnOff_Checked(UseAllOnOff, null);
            else UseAllOnOff_Unchecked(UseAllOnOff, null);
            if (App.SettingsInstance.MusicOnOffSetting)
            {
                MusicOnOff.Content = "On";
            }
            else
            {
                MusicOnOff.Content = "Off";
            }
            ToggleSwitch(SoundEffectsOnOff, null);
            ToggleSwitch(Pseudo3DOnOff, null);
        }

        private void goBack()
        {
            Hide.Begin();
            returnMethod();
        }
        private void ToggleSwitch(object sender, System.Windows.RoutedEventArgs e)
        {
            // SoundFX.PlaySoundEffect(SFX.ButtonClick);

            if (((ToggleSwitch)sender).IsChecked.Value)
            {
                ((ToggleSwitch)sender).Content = "On";
            }
            else
            {
                ((ToggleSwitch)sender).Content = "Off";
            }

            switch (((ToggleSwitch)sender).Name)
            {
                case "MusicOnOff":
                    {
                        SoundHelper.instance.PlayMusic(App.BGMusicPath, ((ToggleSwitch)sender).IsChecked.Value, false);
                        break;
                    }
                case "Pseudo3DOnOff":
                    {
                        if (((ToggleSwitch)sender).IsChecked.Value)
                        {
                            StartAccelerometer();
                        }
                        break;
                    }

            }
        }

        //private void ToggleSwitch_Unchecked(object sender, System.Windows.RoutedEventArgs e)
        //{
        //    ((ToggleSwitch)sender).Content = "Off";
        //    switch (((ToggleSwitch)sender).Name)
        //    {
        //        case "MusicOnOff":
        //            {
        //                SoundHelper.instance.PlayMusic(@"/MemoBoss;component/"+"Sound/Aisle Nine Please.mp3", false, false);
        //                break;
        //            }


        //    }
        //}
        private IUserController _userController;
        private void Show_Completed(object sender, EventArgs e)
        {

            loadControls();

        }

        private void loadControls()
        {
            if (App.SettingsInstance.UseAllImagesSetting) UseAllOnOff_Checked(UseAllOnOff, null);
            else UseAllOnOff_Unchecked(UseAllOnOff, null);
            SetBackgroundPicture();

            btnSubmit.Visibility = Visibility.Collapsed;
            stpAccount.Visibility = Visibility.Collapsed;
            txtLoading.Text = "Loading...";
            txtLoading.Visibility = Visibility.Visible;
            CreateUserControllerIfNeeded();
            if (_userController.IsProcessing)
                return;

           
            _userController.Load(UserLoadScope.Minimal);
            
        }
        void CreateUserControllerIfNeeded()
        {
            if (_userController == null)
            {
                _userController = App.slClient.CreateUserController();
                _userController.RequestFailed += _userController_RequestFailed;
                _userController.RequestCancelled += _userController_RequestFailed;
                _userController.UserLoaded += _userController_UserLoaded;
                _userController.UserUpdated += _userController_UserLoaded;
            }
        }

        void _userController_RequestFailed(object sender, RequestControllerEventArgs<IRequestController> e)
        {
            if (e.Error.ErrorCode != ErrorCode.Undefined)
            {
                string errorString = "";
                errorString += "\n" + e.Error.Message;
                foreach (KeyValuePair<string, string> kvp in e.Error.Arguments) 
                {
                    errorString += "\n" + kvp.Key+" - "+ kvp.Value;
                }
                MessageBox.Show("Oops! There was an error while updating your scoreloop account:" + errorString + "\n ");
            }
            else
            {
                txtLoading.Text = "Unable to connect...";
            }
        }
        void _userController_UserLoaded(object sender, RequestControllerEventArgs<IUserController> e)
        {
            txtLogin.Text = _userController.User.Login;
            txtEmail.Text = _userController.User.Email;
            btnSubmit.Visibility = Visibility.Visible;
            stpAccount.Visibility = Visibility.Visible;
            txtLoading.Visibility = Visibility.Collapsed;
        }


        private void btnBack_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            goBack();
        }

        private void UseAllOnOff_Checked(object sender, RoutedEventArgs e)
        {
            ((ToggleSwitch)sender).Content = "Use all pictures";
            btnGrdCollection.IsHitTestVisible = false;
            btnGrdCollection.Opacity = 0.3;

            txtImages.Text = string.Format("Images - {0} available", ImageCollection.getTotalImagesCountInMediaLibrary());
        }

        private void UseAllOnOff_Unchecked(object sender, RoutedEventArgs e)
        {
            ((ToggleSwitch)sender).Content = "Select pictures manually";
            btnGrdCollection.IsHitTestVisible = true;
            btnGrdCollection.Opacity = 1;
            txtImages.Text = string.Format("Images - {0} selected", App.collection.PicturesCollection.Count);
        }

        private void Btn_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Push.Stop();
            Push.Children.ToList().ForEach(a => Storyboard.SetTarget(a, (DependencyObject)sender));
            Push.Begin();
        }

        private void Btn_MouseLeave(object sender, MouseEventArgs e)
        {
            Release.Stop();
            Release.Children.ToList().ForEach(a => Storyboard.SetTarget(a, (DependencyObject)sender));
            Release.Begin();
        }

        private void btnCollection_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            SoundFX.PlaySoundEffect(SFX.ButtonClick);
            NavigateToCollectionPage();
        }

        public void ExitScreen()
        {
            if (scoreloopPopup != null && scoreloopPopup.IsOpen)
            {
                scoreloopPopupDiag.ReturnDefault();
            }
            else
            {
                this.Hide.Begin();
                returnMethod();
            }
        }

        private void btnSubmit_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Scoreloop.CoreSocial.API.Model.User u = _userController.User;

            showPopup(ScoreloopProfileDialogCallback, u.Login, u.Email);

        }

        Popup scoreloopPopup = null;
        ScoreloopDialog scoreloopPopupDiag;
        private void showPopup(Action<bool, string, string> callback, string login, string email)
        {
            SuspendLayout();
            if (scoreloopPopup == null)
            {
                scoreloopPopup = new Popup();


            }
            scoreloopPopupDiag = new ScoreloopDialog(callback, login, email);


            scoreloopPopup.Child = scoreloopPopupDiag;




            scoreloopPopup.IsOpen = true;
            scoreloopPopupDiag.Opacity = 0;
            scoreloopPopupDiag.UpdateLayout();
            scoreloopPopup.VerticalOffset = 50;//(App.Current.RootVisual as FrameworkElement).ActualHeight / 2 - scoreloopPopupDiag.ActualHeight / 2;

            scoreloopPopup.HorizontalOffset = (App.Current.RootVisual as FrameworkElement).ActualWidth / 2 - scoreloopPopupDiag.ActualWidth / 2;

            scoreloopPopupDiag.Opacity = 1;
            //CardsPanel.Visibility = System.Windows.Visibility.Collapsed;


        }
        void ScoreloopProfileDialogCallback(bool result, string login, string email)
        {

            if (result)
            {
                if (scoreloopPopup != null)
                    scoreloopPopup.IsOpen = false;
                ReleaseLayout();
                _userController.Update(login, email);

            }
            else
            {
                if (scoreloopPopup != null)
                    scoreloopPopup.IsOpen = false;
                ReleaseLayout();
            }
        }
        void SuspendLayout()
        {
            LayoutRoot.IsHitTestVisible = false;

        }
        void ReleaseLayout()
        {
            LayoutRoot.IsHitTestVisible = true;

        }

    }
}
